package sdk

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/event"
	fabAPI "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab"
	"log"
)

//func DiscoverLocalPeers(ctxProvider contextAPI.ClientProvider, expectedPeers int) ([]fabAPI.Peer, error) {
//	ctx, err := contextImpl.NewLocal(ctxProvider)
//	if err != nil {
//		return nil, fmt.Errorf("error creating local context: %v", err)
//	}
//
//	discoveredPeers, err := retry.NewInvoker(retry.New(retry.TestRetryOpts)).Invoke(
//		func() (interface{}, error) {
//			peers, serviceErr := ctx.LocalDiscoveryService().GetPeers()
//			if serviceErr != nil {
//				return nil, fmt.Errorf("getting peers for MSP [%s] error: %v", ctx.Identifier().MSPID, serviceErr)
//			}
//			if len(peers) < expectedPeers {
//				return nil, status.New(status.TestStatus, status.GenericTransient.ToInt32(), fmt.Sprintf("Expecting %d peers but got %d", expectedPeers, len(peers)), nil)
//			}
//			return peers, nil
//		},
//	)
//	if err != nil {
//		return nil, err
//	}
//
//	return discoveredPeers.([]fabAPI.Peer), nil
//}

var CCEvent <-chan *fabAPI.CCEvent

func RegitserChaincodeEvent(client *event.Client, chaincodeID string) fabAPI.Registration {
	eventName := "chaincode-event"
	reg, ccEvent, err := client.RegisterChaincodeEvent(chaincodeID, eventName)
	if err != nil {
		fmt.Println("   >> 注册链码事件失败: %s", err)
	}
	CCEvent = ccEvent
	fmt.Println("   >> 链码事件注册成功")
	return reg
}

var BlEvent <-chan *fabAPI.BlockEvent

func RegitserBlockEvent(ec *event.Client) fabAPI.Registration {
	// Register monitor block event
	beReg, blEvent, err := ec.RegisterBlockEvent()
	if err != nil {
		log.Printf("   >> 注册区块事件失败: %v", err)
	}
	fmt.Println("   >> 区块事件注册成功")
	BlEvent = blEvent
	return beReg
}
